package fon.test.webservice;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class GGLXMLParser {
	private String xmlString;
	private static String ROOT_TAG = "array";
	private static String FUNC_ID_TAG = "func_id";
	private static String VERSION_TAG = "version";
	private ArrayList<ArrayList> result;
	private int flag=0;//0 common;1 ite
	private ArrayList<String> keyTag;
	private ArrayList<String> valueTag;
	
	public GGLXMLParser(String xml)
	{
		this.xmlString = xml;
	}

	public String getElementValueFromName(String elementName){

			DocumentBuilderFactory dbf =
					DocumentBuilderFactory.newInstance();
			String output="";
			DocumentBuilder db;
				try {
					db = dbf.newDocumentBuilder();
					InputSource is = new InputSource();
					is.setCharacterStream(new StringReader(xmlString));

					Document doc = db.parse(is);
					NodeList currentPointedNodes = doc.getElementsByTagName(elementName);
					Element line = (Element) currentPointedNodes.item(0);
					output = getCharacterDataFromElement(line);
					return output;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "?"; 
			// iterate the children
/*			for (int i = 0; i < firstLevelNodes.getLength(); i++) {
				Element element = (Element) firstLevelNodes.item(i);

				NodeList name = element.getElementsByTagName("user_picture_uri");
				Element line = (Element) name.item(0);
				output += "user_picture_uri : "+"("+i+")" + getCharacterDataFromElement(line)+"\n";
				//System.out.println("user_picture_uri: " + getCharacterDataFromElement(line));
				
				/*
				 * NodeList title = element.getElementsByTagName("review_picture_uri");
				line = (Element) title.item(0);
				System.out.println("Title: " + getCharacterDataFromElement(line));
				*/
			//}
			
			//return output;
		
	}
	public NodeList getElementFromName(String elementName){

		DocumentBuilderFactory dbf =
				DocumentBuilderFactory.newInstance();

		DocumentBuilder db;
			try {
				db = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xmlString));

				Document doc = db.parse(is);
				NodeList currentPointedNode = doc.getElementsByTagName(elementName);
				
				return currentPointedNode;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null; 
	
}
	public static String getCharacterDataFromElement(Element e) {
	    Node child = e.getFirstChild();
	    if (child instanceof CharacterData) {
	       CharacterData cd = (CharacterData) child;
	       return cd.getData();
	    }
	    return "?";
	  }
	public ArrayList getResult(){

		NodeList root_level = getElementFromName(ROOT_TAG);

		keyTag = new ArrayList<String>();
		valueTag = new ArrayList<String>();
		result = new ArrayList<ArrayList>();
		flag = 0;
		getAllNode(root_level);
	  	if(flag==0&&result.isEmpty()){//edited 22/11/11 (for only one level)
		    //	  Log.d("gugulog","===== mark =====");
		    			  result.add(keyTag);
		    			  result.add(valueTag);
		  	}//
		return result;
	}
	public void getAllNode(NodeList nodelist)
	{
		
	    for(int i=0; i<nodelist.getLength(); i++){
	      Node childNode = nodelist.item(i);

	      if(!childNode.getNodeName().startsWith("#")&&!childNode.getNodeName().equalsIgnoreCase(this.ROOT_TAG))
	      {
	    	  
	    	  //if(getCharacterDataFromElement((Element)childNode)==null)
	    	  if(getCharacterDataFromElement((Element)childNode).matches("[\\s]+[^\\S]+"))
	    	  {
	    		  //String empty = childNode.getNodeName();
	    	  }
	      else if(keyTag.isEmpty() || !keyTag.contains(childNode.getNodeName()))
	    	  {
	    		  keyTag.add(childNode.getNodeName());
	    		  valueTag.add(getCharacterDataFromElement((Element)childNode));
	    		  //Log.d("gugulog","id: "+childNode.getNodeName());
	    	  }
	    	  else if(childNode.getNodeName().equalsIgnoreCase(keyTag.get(keyTag.size()-1))){
	    		  valueTag.set(keyTag.indexOf(childNode.getNodeName()), getCharacterDataFromElement((Element)childNode));
	    		  //Log.d("gugulog","=====id: "+childNode.getNodeName()+" value:"+getCharacterDataFromElement((Element)childNode));
	    		  //Log.d("gugulog","===== commit =====");
	    		  result.add(valueTag);
	    	  }
	    	  else{
	    		  if(flag==0){
	    			  //Log.d("gugulog","===== commit =====");
	    			  result.add(keyTag);
	    			  result.add(valueTag);
	    			  flag = 1;
	    		  }
	    		  valueTag.set(keyTag.indexOf(childNode.getNodeName()), getCharacterDataFromElement((Element)childNode));
	    		  //Log.d("gugulog",childNode.getNodeType()+"=====id: "+childNode.getNodeName()+" value:"+getCharacterDataFromElement((Element)childNode).length());
	    		  
	    	  }
	    		  

		      
    	  		}
	      NodeList children = childNode.getChildNodes();
	      if (children != null)
	      {
	    	  //Log.d("gugulog","===== BEFORE ====="); 
	    	  getAllNode(children);
	    	  
	    	  

	      }
	      
	    }
		
	}
	public String getFuncId(){
		return getElementValueFromName(FUNC_ID_TAG);
	}
	public String getVersion(){
		return getElementValueFromName(VERSION_TAG);
	}
}
